package com.roocon.design_pattern.chapter06_two_termination;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientHandler implements Runnable {

  private final Socket mSoket;

  private volatile boolean running = true;

  public ClientHandler(Socket mSoket) {
    this.mSoket = mSoket;
  }

  @Override public void run() {
    try (
        InputStream inputStream = mSoket.getInputStream();
        OutputStream outputStream = mSoket.getOutputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        PrintWriter writer = new PrintWriter(outputStream)
    ) {
      while (running) {
        String message = br.readLine();
        if (message == null) {
          break;
        }
        System.out.println("Come from ClientJoin ->" + message);
        writer.write("Echo " + message +"\n");
        writer.flush();
      }
    } catch (IOException e) {
      //有很多种异常，判断那种异常时可以去掉的
      //如：1. 端口未绑定；Socket broker 等等
      //e.printStackTrace();
      this.running = false;
    }finally {
      this.stop();
    }
  }

  public void stop() {
    if (!running) return;
    this.running = false;
    try {
      this.mSoket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
